package flex.cc.uac.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import flex.cc.PublicUtil;
import flex.cc.base.dto.LoginAuthDto;
import flex.cc.base.enums.ErrorCodeEnum;
import flex.cc.uac.dao.UacCompanyDao;
import flex.cc.uac.dao.UacCompanyUserDao;
import flex.cc.uac.entity.UacCompanyEntity;
import flex.cc.uac.entity.UacCompanyUserEntity;
import flex.cc.uac.exceptions.UacBizException;
import flex.cc.uac.service.UacCompanyService;
import flex.cc.uac.vo.CompanyTreeVo;
import lombok.extern.slf4j.Slf4j;


@Service("uacCompanyService")
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class UacCompanyServiceImpl extends ServiceImpl<UacCompanyDao, UacCompanyEntity> implements UacCompanyService {

    @Resource
    private UacCompanyDao uacCompanyDao;
    
    @Resource
    private UacCompanyUserDao uacCompanyUserDao;
    
    private final String BASEPATH = "00000000";

    /**
     * 保存组织
     * @param uacCompany
     * @param loginAuthDto
     */
	@Override
	public void saveUacCompany(UacCompanyEntity uacCompany, LoginAuthDto loginAuthDto) {
		UacCompanyEntity uacCompanyEntity = this.getById(uacCompany.getComCode());
        if (uacCompanyEntity == null || PublicUtil.isEmpty(uacCompanyEntity.getComCode())) { // 新增
        	// 上级组织全路径
        	if(uacCompany.getComLevel().compareTo(1) > 0) {
        		UacCompanyEntity upperCompany = this.getById(uacCompany.getUpperComCode());
        		uacCompany.setUpperPath(upperCompany.getUpperPath() + "," + upperCompany.getComCode());
        	}else{
        		uacCompany.setUpperPath(uacCompany.getUpperComCode());
        	}
        	// 组织简称，为空默认与名称一致
        	if(PublicUtil.isEmpty(uacCompany.getComShortName())) {
        		uacCompany.setComShortName(uacCompany.getComCName());
        	}
        	uacCompany.setUpdateInfo(loginAuthDto, true);
        	this.save(uacCompany);
        } else { // 修改
        	uacCompanyEntity.setComCName(uacCompany.getComCName()); // 组织名称
        	// 组织简称，为空默认与名称一致
        	if(PublicUtil.isEmpty(uacCompany.getComShortName())) {
        		uacCompanyEntity.setComShortName(uacCompany.getComCName());
        	} else {
        		uacCompanyEntity.setComShortName(uacCompany.getComShortName());
        	}
        	uacCompanyEntity.setComEName(uacCompany.getComEName()); // 组织英文名称
        	uacCompanyEntity.setValidStatus(uacCompany.getValidStatus()); // 是否有效
        	uacCompanyEntity.setRemark(uacCompany.getRemark()); // 备注
        	uacCompanyEntity.setUpdateInfo(loginAuthDto, false);
        	boolean result = this.updateById(uacCompanyEntity);
            if (!result) {
            	// 更新组织信息失败
                throw new UacBizException(ErrorCodeEnum.UAC10015006, uacCompany.getComCode());
            }
        }
    }
	
	/**
     * 删除组织
     * @param comCode
     * @param loginAuthDto
     */
	public void delUacCompanyByCode(String comCode, LoginAuthDto loginAuthDto) {
		UacCompanyEntity uacCompanyEntity = this.getById(comCode);
		if (uacCompanyEntity == null) {
        	// 找不到组织信息
            throw new UacBizException(ErrorCodeEnum.UAC10015004, comCode);
        }
		
		// 该组织下还存在子节点，不能将其删除
		List<CompanyTreeVo> companyTree = this.getCompanyTreeVo(uacCompanyEntity.getComCode(), null, null, null);
		System.out.println(companyTree.size());
		if(companyTree != null && companyTree.size() > 0) {
			// 该组织下还存在子节点，不能将其删除
            throw new UacBizException(ErrorCodeEnum.UAC10015007, comCode);
		}
		
		// 该组织下绑定的用户，不能将其删除
		List<UacCompanyUserEntity> companyUser = this.uacCompanyUserDao.selectList(new QueryWrapper<UacCompanyUserEntity>().eq("com_code", uacCompanyEntity.getComCode()));
		System.out.println(companyUser.size());
		if(companyUser != null && companyUser.size() > 0) {
			// 该组织下绑定有用户，不能将其删除
            throw new UacBizException(ErrorCodeEnum.UAC10015008, comCode);
		}
		
		// 删除组织
		boolean result = this.removeById(comCode);
		if (!result) {
            log.error("删除组织失败 comCode={}", comCode);
            throw new UacBizException(ErrorCodeEnum.UAC10015010, comCode);
        }
	}
	
	
	/**
	 * 查询当前机构
	 * @param comCode
	 * @return
	 */
    @Override
    public List<CompanyTreeVo> getCompanyVo(String comCode) {
    	List<CompanyTreeVo> companyVo = uacCompanyDao.getCompanyVo(comCode);
        return companyVo;
    }
    
    /**
     * 查询所有下级机构
     * @param comCode：当前机构
     * @param level：要展示的机构最高层级
     * @param userFlag：是否考虑用户归属机构
     * @return
     */
    @Override
    public List<CompanyTreeVo> getCompanyTreeVo(String comCode, String maxLevel, String userFlag, LoginAuthDto loginAuthDto) {
    	List<CompanyTreeVo> companyTreeVo = null;
    	if("true".equals(userFlag) && !PublicUtil.isEmpty(loginAuthDto.getBelongComCode())) {
    		// 查询当前机构是否是归属机构下级
    		List<CompanyTreeVo> MyChild = comCode.equals(loginAuthDto.getBelongComCode()) ? null : uacCompanyDao.getCompanyTreeByPath(loginAuthDto.getBelongComCode(), 0, comCode);
			if(comCode.equals(loginAuthDto.getBelongComCode()) || !PublicUtil.isEmpty(MyChild)) {
				// 当前机构=归属机构
				if(PublicUtil.isEmpty(maxLevel)) {
					companyTreeVo = uacCompanyDao.getCompanyTreeVo(comCode);
				} else {
					companyTreeVo = uacCompanyDao.getCompanyTreeByPath(comCode, Integer.parseInt(maxLevel), null);
				}
			} else {
				// 判断归属机构是否是当前机构的下级
    			List<CompanyTreeVo> comChild = uacCompanyDao.getCompanyTreeByPath(comCode, 0, loginAuthDto.getBelongComCode());
    			if(!PublicUtil.isEmpty(comChild)) { // 归属机构是当前机构的下级
    				// 查询坐席的归属机构
    	    		UacCompanyEntity userCompany = this.getById(loginAuthDto.getBelongComCode());
    	    		String[] upperPath = userCompany.getUpperPath().split(",");
    	    		if(PublicUtil.isEmpty(maxLevel)) {
        				boolean isOk = false;
        				for(String code : upperPath) {
        					if(isOk) {
        						companyTreeVo = uacCompanyDao.getCompanyVo(code);
        						isOk = false;
        						break;
        					}
        					// 当机构路径匹配上时，下一个值就是要找的机构
        					if(code.equals(comCode)) {
        						isOk = true;
        					}
        				}
        				if(isOk) { // 找的就是归属机构
        					companyTreeVo = comChild;
        				}
    	    		} else if(userCompany.getComLevel().compareTo(new Integer(maxLevel)) == 0) {
    	    			// 指定找归属机构
    	    			companyTreeVo = comChild;
    	    		} else if(userCompany.getComLevel().compareTo(new Integer(maxLevel)) > 0){
    	    			// 找归宿机构的上级
    	    			companyTreeVo = uacCompanyDao.getCompanyVo(upperPath[Integer.parseInt(maxLevel)]);
    	    		} else {
    	    			companyTreeVo = uacCompanyDao.getCompanyTreeByPath(userCompany.getComCode(), Integer.parseInt(maxLevel), null);
    	    		}
    			}
			}
    	} else {
    		if(PublicUtil.isEmpty(maxLevel)) {
    			// 未指定机构级别，单纯查询下级机构
    			companyTreeVo = uacCompanyDao.getCompanyTreeVo(comCode);
    		} else {
    			// 查询指定机构下，指定级别机构
    			companyTreeVo = uacCompanyDao.getCompanyTreeByPath(comCode, Integer.parseInt(maxLevel), null);
    		}
    	}
        return companyTreeVo;
    }
    
    /**
	 * 根据机构获取所有父级及列表
	 * @param comCode
	 * @param level
	 * @param userFlag
	 * @return
	 */
    @Override
    public Map<String, Object> findComPathList(String comCode, String maxLevel, String userFlag, LoginAuthDto loginAuthDto){
    	Map<String, Object> map=new HashMap<String, Object>();
    	UacCompanyEntity uacCompany = this.getOne(new QueryWrapper<UacCompanyEntity>().eq("com_code", comCode));
    	String comPath = uacCompany.getUpperPath();
    	if(!PublicUtil.isEmpty(comPath)) {
    		String[] paths = comPath.split(",");
    		// 学校
    		if("1".equals(maxLevel)) {
    			List<CompanyTreeVo> companyTreeVo = getCompanyTreeVo(paths[0], maxLevel, userFlag, loginAuthDto);
				map.put("provinceList", companyTreeVo);
				map.put("province", paths.length > 1 ? paths[1] : uacCompany.getComCode());
			} else {
				map.put("provinceList", null);
				map.put("province", "");
			}
    		// 部门
			if(paths.length > 0) {
				List<CompanyTreeVo> companyTreeVo = null;
				String upperCode = null;
				if("1".equals(maxLevel)) {
					upperCode = paths.length > 1 ? paths[1] : uacCompany.getComCode();
					companyTreeVo = getCompanyTreeVo(upperCode, null, userFlag, loginAuthDto);
				}else if("2".equals(maxLevel)) {
					upperCode = paths[0];
					companyTreeVo = getCompanyTreeVo(upperCode, maxLevel, userFlag, loginAuthDto);
				}
				String city = "";
				if(paths.length == 2) {
					city = uacCompany.getComCode();
				} else if(paths.length >= 3) {
					city = paths[2];
				}
				map.put("cityList", companyTreeVo);
				map.put("city", city);
			}
			// 中心
			if(paths.length > 1) {
				List<CompanyTreeVo> companyTreeVo = null;
				String upperCode = null;
				if("3".equals(maxLevel)) {
					upperCode = paths[0];
					companyTreeVo = getCompanyTreeVo(upperCode, maxLevel, userFlag, loginAuthDto);
				} else {
					upperCode = paths.length > 2 ? paths[2] : uacCompany.getComCode();
					companyTreeVo = getCompanyTreeVo(upperCode, null, userFlag, loginAuthDto);
				}
				String area = "";
				if(paths.length == 3) {
					area = uacCompany.getComCode();
				} else if(paths.length >= 4) {
					area = paths[3];
				}
				map.put("areaList", companyTreeVo);
				map.put("area", area);
			}
			// 业务组
			if(paths.length > 2) {
				List<CompanyTreeVo> companyTreeVo = null;
				String upperCode = null;
				if("4".equals(maxLevel)) {
					upperCode = paths[0];
					companyTreeVo = getCompanyTreeVo(upperCode, maxLevel, userFlag, loginAuthDto);
				} else {
					upperCode = paths.length > 3 ? paths[3] : uacCompany.getComCode();
					companyTreeVo = getCompanyTreeVo(upperCode, null, userFlag, loginAuthDto);
				}
				String yewu = "";
				if(paths.length == 4) {
					yewu = uacCompany.getComCode();
				} else if(paths.length >= 5) {
					yewu = paths[4];
				}
				map.put("yewuList", companyTreeVo);
				map.put("yewu", yewu);
			}
			map.put("info", "1");
			map.put("level", paths.length);
    	} else {
    		map.put("info", "组织机构路径为空");
    	}
    	return map;
    }
	
	/**
	 * 获取所传机构及其下属机构
	 */
	public List<CompanyTreeVo> getComAndsubComCodeVo(String comCode) {
		List<CompanyTreeVo> companyVo = uacCompanyDao.getComAndsubComCodeVo(comCode);
        return companyVo;
	}
}